/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.    
 */
using System;
using Parser = Velocity4Net.Runtime.Parse.Parser;
using MethodInvocationException = Velocity4Net.Errors.MethodInvocationException;
using InternalContextAdapter = Velocity4Net.Ctx.InternalContextAdapter;
namespace Velocity4Net.Runtime.Parse.AST
{

    /// <summary>  Handles the equivalence operator
    /// *
    /// <arg1>  == <arg2>
    /// *
    /// This operator requires that the LHS and RHS are both of the
    /// same Class.
    /// *
    /// </summary>
    /// <version> $Id: ASTEQNode.cs,v 1.3 2003/10/27 13:54:10 corts Exp $
    ///
    /// </version>
    public class ASTEQNode : SimpleNode
    {
        public ASTEQNode(int id) : base(id) { }

        public ASTEQNode(Parser p, int id) : base(p, id) { }

        /**
         *   Calculates the value of the logical expression
         *
         *     arg1 == arg2
         *
         *   All class types are supported.   Uses equals() to
         *   determine equivalence.  This should work as we represent
         *   with the types we already support, and anything else that
         *   implements equals() to mean more than identical references.
         *
         *
         *  @param context  internal context used to evaluate the LHS and RHS
         *  @return true if equivalent, false if not equivalent,
         *          false if not compatible arguments, or false
         *          if either LHS or RHS is null
         * @throws MethodInvocationException
         */
        public override bool Evaluate(InternalContextAdapter context)
        {
            Object left = jjtGetChild(0).GetValue(context);
            Object right = jjtGetChild(1).GetValue(context);

            /*
             *  convert to Number if applicable
             */
            try
            {
                decimal l = Convert.ToDecimal(left);
                decimal r = Convert.ToDecimal(right);
                return l == r;
            }
            catch
            {
            }
            //if (left is TemplateNumber)
            //{
            //   left = ( (TemplateNumber) left).getAsNumber();
            //}
            //if (right is TemplateNumber)
            //{
            //   right = ( (TemplateNumber) right).getAsNumber();
            //}

            /*
             * If comparing Numbers we do not care about the Class.
             */
            //if (left is Number && right is Number)
            //{
            //    return MathUtils.compare( (Number)left, (Number)right) == 0;
            //}

            /**
             * if both are not null, then assume that if one class
             * is a subclass of the other that we should use the equals operator
             */
            if (left != null && right != null &&
                (left.GetType().IsAssignableFrom(right.GetType()) ||
                 right.GetType().IsAssignableFrom(left.GetType())))
            {
                return left.Equals(right);
            }

            /*
             * Ok, time to compare string values
             */
            left = (left == null) ? null : left.ToString();
            right = (right == null) ? null : right.ToString();

            if (left == null && right == null)
            {
                if (log.isDebugEnabled())
                {
                    log.debug("Both right (" + getLiteral(false) + " and left "
                              + getLiteral(true) + " sides of '==' operation returned null."
                              + "If references, they may not be in the context."
                              + GetLocation(context));
                }
                return true;
            }
            else if (left == null || right == null)
            {
                if (log.isDebugEnabled())
                {
                    log.debug((left == null ? "Left" : "Right")
                            + " side (" + getLiteral(left == null)
                            + ") of '==' operation has null value. If it is a "
                            + "reference, it may not be in the context or its "
                            + "toString() returned null. " + GetLocation(context));

                }
                return false;
            }
            else
            {
                return left.Equals(right);
            }
        }

        private String getLiteral(bool left)
        {
            return jjtGetChild(left ? 0 : 1).Literal();
        }

        /**
         * @see org.apache.velocity.runtime.parser.node.SimpleNode#value(org.apache.velocity.context.InternalContextAdapter)
         */
        public override Object GetValue(InternalContextAdapter context)
        {
            return Evaluate(context) ? true : false;
        }
    }

}
